package handlers

import (
	"car-master/cache"
	"car-master/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func HouseAdd(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.House{

		Title:   title,
		Content: content,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}

func HoseOrderAdd(c *gin.Context) {
	num, _ := strconv.Atoi(c.PostForm("num"))
	price, _ := strconv.Atoi(c.PostForm("price"))
	hid, _ := strconv.Atoi(c.PostForm("hid"))
	data := models.HouseOrder{
		Num:   num,
		Price: price,
		Hid:   hid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
func HouseList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "2"))
	offset := (page - 1) * pageSize
	/*
		SELECT
		house_orders.hid as OrderID,
		houses.title as Title,
		houses.content as content,
		house_orders.num as Num,
		house_orders.price as Price
		FROM
		houses
		LEFT JOIN house_orders ON house_orders.hid=houses.id
	*/
	var arr []models.HouseList
	redis_key := "redis_list" + strconv.Itoa(page)
	redsData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redsData == "" {
		models.DB.Table("houses").Select(
			"house_orders.hid as OrderID",
			"houses.title as Title",
			"houses.content as content",
			"house_orders.num as Num",
			"house_orders.price as Price",
		).
			Joins("LEFT JOIN house_orders ON house_orders.hid=houses.id").
			Offset(offset).Limit(pageSize).Find(&arr)
		jsonData, _ := json.Marshal(arr)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redsData), &arr)
	}
	var total int64
	models.DB.Model(&models.House{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"list":  arr,
		"total": total,
	})

}
func HouseDetail(c *gin.Context) {
	id := c.Query("id")
	var arr models.HouseList
	redis_key := "redis_detail" + id
	redsData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redsData == "" {
		models.DB.Table("houses").Select(
			"house_orders.hid as OrderID",
			"houses.title as Title",
			"houses.content as content",
			"house_orders.num as Num",
			"house_orders.price as Price",
		).
			Joins("LEFT JOIN house_orders ON house_orders.hid=houses.id").
			Where("houses.id=?", id).Find(&arr)
		jsonData, _ := json.Marshal(arr)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redsData), &arr)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})
}
